import {
  AreaChartOutlined,
  EllipsisOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import {
  Button,
  Col,
  Dropdown,
  Form,
  Input,
  Modal,
  Row,
  Switch,
  Tooltip,
} from 'antd';
import { useRef } from 'react';
import { request, history, connect, useSelector } from 'umi';
import './ist.css';
import { getTime } from '@/utils/time';
// import { getLouList, dels } from '@/api/getToutist';
import { useAddKey } from '@/pages/hooks/index';
// import PubSub from 'pubsub-js';

const { Search } = Input;

type GithubIssueItem = {
  url: string;
  id: number;
  number: number;
  title: string;
  labels: {
    name: string;
    color: string;
  }[];
  state: string;
  comments: number;
  created_at: string;
  updated_at: string;
  closed_at?: string;
};

const style: React.CSSProperties = { background: '#0092ff' };
const styles: React.CSSProperties = { background: 'red' };
const sty: React.CSSProperties = { color: 'white' };
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}

const list = (props: any) => {
  console.log(props, 'props');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const showModal = () => {
    setIsModalOpen(true);
  };

  const onFinish = (values: any) => {
    console.log('Success:', values);
    props.dispatch({ type: 'house/add', values });
    setIsModalOpen(false);
  };
  // 搜索
  const onSearch = (value: string) => {
    console.log(value);
    props.dispatch({ type: 'house/SEARCH', value });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const actionRef = useRef<ActionType>();

  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>(
    'checkbox',
  );
  // rowSelection object indicates the need for row selection
  const rowSelection: any = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows,
      );
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  // 点击编辑
  const edit = (id: number) => {
    history.push('/home/house/housecontrol/edit', { id });
  };
  // 点击删除
  const del = (id: number) => {
    props.dispatch({ type: 'house/DEL', id });
  };

  // 点击新增
  const addTable = () => {
    showModal();
  };

  // 跳转户型
  const goType = (item: any) => {
    history.push('/home/house/housecontrol/housetype', item);
  };

  const goPicture = (item: any) => {
    history.push('/home/house/housecontrol/picture', item);
  };

  const goTai = (item: any) => {
    history.push('/home/house/housecontrol/tai', item);
  };

  const goSand = (item: any) => {
    history.push('/home/house/housecontrol/sand', item);
  };
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      ellipsis: true,
    },
    {
      title: '标题',
      dataIndex: 'title',
      render: (item, record: any) => {
        const img =
          record.rec_position === 1 ? (
            <img
              loading="lazy"
              src="http://fangadmin.shbwyz.com/static/images/rec.png"
              alt=""
            />
          ) : (
            ''
          );
        return (
          <React.Fragment>
            {item}
            {img}
            {record.img ? (
              <Tooltip
                title={
                  <img
                    className="ll-img"
                    src={`http://fangadmin.shbwyz.com${record.img}`}
                  ></img>
                }
              >
                <AreaChartOutlined />
              </Tooltip>
            ) : (
              ''
            )}
          </React.Fragment>
        );
      },
    },
    {
      title: '所属区域',
      dataIndex: 'address',
      ellipsis: true,
    },
    {
      disable: true,
      title: '价格',
      dataIndex: 'price',
      render: (item: any) => {
        return item === 0 ? (
          <span>待定</span>
        ) : item < 10 ? (
          <span>{item}万/套</span>
        ) : (
          <span>{item}元/m²</span>
        );
      },
    },
    {
      title: '更新时间',
      // key: 'update_time',
      dataIndex: 'update_time',
      render: (item) => {
        return getTime(item);
      },
    },
    // {
    //   title: '更新时间',
    //   dataIndex: 'create_time',
    //   valueType: 'dateRange',
    //   hideInTable: true,
    // },
    {
      disable: true,
      title: '排序',
      dataIndex: 'ordid',
      // search: false,
    },
    {
      disable: true,
      title: '状态',
      dataIndex: 'sale_status',
      // search: false,
      render: (item) => {
        return (
          <Switch
            checkedChildren="正常"
            unCheckedChildren="禁用"
            defaultChecked={item === 0 ? false : true}
          />
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => {
        return (
          <div>
            <Row gutter={8}>
              <Col className="gutter-row" span={8}>
                <Button
                  onClick={() => goType(record)}
                  size="small"
                  style={style}
                  className="btn"
                >
                  户型
                </Button>
              </Col>
              <Col className="gutter-row" span={8}>
                <Button
                  onClick={() => goPicture(record)}
                  size="small"
                  style={style}
                  className="btn"
                >
                  相册
                </Button>
              </Col>
              <Col className="gutter-row" span={8}>
                <Button
                  onClick={() => goTai(record)}
                  size="small"
                  style={style}
                  className="btn"
                >
                  动态
                </Button>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col className="gutter-row" span={8}>
                <Button
                  onClick={() => goSand(record)}
                  size="small"
                  style={style}
                  className="btn"
                >
                  沙盘
                </Button>
              </Col>
              <Col className="gutter-row" span={8}>
                <Button
                  size="small"
                  style={style}
                  className="btn"
                  onClick={() => {
                    edit(record.id);
                  }}
                >
                  编辑
                </Button>
              </Col>
              <Col className="gutter-row" span={8}>
                <Button
                  onClick={() => del(record.id)}
                  size="small"
                  style={styles}
                  className="btn"
                >
                  删除
                </Button>
              </Col>
            </Row>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Search
        placeholder="input search text"
        allowClear
        enterButton="Search"
        size="large"
        onSearch={onSearch}
      />
      <ProTable<GithubIssueItem>
        columns={columns}
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        actionRef={actionRef}
        cardBordered
        dataSource={useAddKey(props.data)}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          onChange(value) {
            // console.log('value: ', value);
          },
        }}
        rowKey="id"
        search={false}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
          onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        headerTitle="高级表格"
        toolBarRender={() => [
          <Button
            onClick={addTable}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新建
          </Button>,
          <Dropdown
            key="menu"
            menu={{
              items: [
                {
                  label: '1st item',
                  key: '1',
                },
                {
                  label: '2nd item',
                  key: '1',
                },
                {
                  label: '3rd item',
                  key: '1',
                },
              ],
            }}
          >
            <Button>
              <EllipsisOutlined />
            </Button>
          </Dropdown>,
        ]}
      />
      <Modal title="Basic Modal" open={isModalOpen} footer={null}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="所属区域"
            name="address"
            rules={[{ required: true, message: '' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="价格"
            name="price"
            rules={[{ required: true, message: '' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="排序"
            name="ordid"
            rules={[{ required: true, message: '' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
const mapStateToProps = (state: any) => {
  console.log(state);
  return {
    data: state.house.list,
  };
};
export default connect(mapStateToProps)(list);
